<?php
/**
 *考勤系统把病假，陪产假超过7天未上传证明的转为事假处理
 *@author coldarmy
 * */
apf_require_class('Oa_Job_Attendance_Abstract');
apf_require_class('Bll_Attendance_DailyReport');
class Oa_Job_Attendance_ConvertToLeaveStatus extends Oa_Job_Attendance_Abstract {

    /** 考勤系统读 **/
    private $readdb = "attendance_slave";
    /** 考勤系统写 **/
    private $writedb = "attendance_master";
    private $report_bll =null;
    public function run($params){
        $this->log("开始检测...");
        $this->deal_with_out_time_data();
        $this->log("检测完毕");
    }

    /**
     * 处理未上传证明的假，如果是28日早上则发送本月内转了的数据给HR
     *
     * @access private
     * @return void
     */
    private function deal_with_out_time_data() {
        $start_time = mktime(0,0,0,date('m'),date('d') - 15,date('Y'));
        //$start_time = date('Y-m-d H:i:s',$start_time);
        $start = 0;
        $row = 300;
        $now = time();
        $have_done = array();
        $this->report_bll = new Bll_Attendance_DailyReport();
        while(true) {
            $sql = "SELECT id,apply_time,type,img FROM leave_record WHERE (type = '病假') AND apply_time_ext > $start_time limit $start,$row";
            $back = $this->get_db_rows($sql, $this->readdb, array());
            if(empty($back)) {
                break;
            }
            $start += $row;
            foreach ($back as $key => $val) {
                $apply = strtotime($val['apply_time']);
                //echo $val['apply_time'],"---";echo date('Y-m-d H:i:s',$now),"--",$apply,"__",$now,"__",$start_time,"\n";
                if(($now - $apply) > 604800 && empty($val['img'])) {
                    $this->update_out_data($val['id'],$val['type']);
                    $have_done[] = $val['id'];
                }
            }
        }
        $special_day = $this->get_settlement_day();
        /** 特殊日发送邮件给HR **/
        if(date('d') == '28') {
            $this->send_mail_inform_hr($special_day);
        }
        var_dump($have_done);
    }

    /**
     * 处理数据，更新为事假
     *
     * @param int $id
     * @access private
     * @return empty or int
     */
    private function update_out_data($id,$type) {
        $back = '';
        if(empty($id) || !is_numeric($id)) {
            return $back;
        }
        $u_sql = "UPDATE leave_record set type = '事假' WHERE id = $id";
        $back = $this->execute($u_sql, array(), $this->writedb);
        $this->update_day_record($id);
        if($back) {
            $this->log("ID：$id 更新完成");
            /** 把日志写入到日志表中 **/
            $now = time();
            $month = date('Ym');
            $i_sql = "REPLACE INTO leave_convert_log(leave_id,updated,applymonth,origin_type) VALUE($id,{$now},{$month},'{$type}')";
            $result = $this->execute($i_sql, array(), $this->writedb);
        }
        return $back;
    }

    private function send_mail_inform_hr($special_day) {
        $start = mktime(0,0,0,date('m')-1,$special_day,date('Y'));
        $end = mktime(0,0,0,date('m'),28,date('y'));
        $sql = "SELECT leave_id,origin_type FROM leave_convert_log WHERE updated > $start AND updated < $end";
        $tmp = $this->get_db_rows($sql,$this->readdb,array());
        if(empty($tmp)) {
            return;
        }
        $temp = array();
        $origin = array();
        foreach ($tmp as $key => $val) {
            $temp[] = $val['leave_id'];
            $origin[$val['leave_id']] = $val['origin_type'];
        }
        $ids = implode(',',$temp);
        $w_sql = "SELECT id,user_id,apply_time,start_time,end_time,leave_time FROM leave_record where id in ($ids)";
        $wait_content = $this->get_db_rows($w_sql, $this->readdb, array());
        if(empty($wait_content)) {
            $this->log("没有自动转为事假的数据");
            die();
        }
        $send = array();
        foreach ($wait_content as $key => $val) {
            $user = $this->get_user_info_by_id($val['user_id']);
            $val['user_name'] = $user[0]['name'];
            $val['user_code'] = $user[0]['code'];
            $val['department'] = $user[0]['city_name'].$user[0]['department_name'];
            $val['type'] = $origin[$val['id']];
            $send[] = $val;
        }
        $mailcontent = "本月自动转换为事假情况统计：<table border='1' cellspacing='1' cellpadding='1'>
                        <tr><td>姓名</td><td>员工号</td><td>部门</td><td>申请时间</td><td>开始时间</td><td>结束时间</td><td>天数</td><td>原假类型</td></tr>";
        foreach ($send as $key => $val) {
            $mailcontent .= "<tr><td>{$val['user_name']}</td><td>{$val['user_code']}</td><td>{$val['department']}</td><td>{$val['apply_time']}</td><td>{$val['start_time']}</td><td>{$val['end_time']}</td><td>{$val['leave_time']}</td><td>{$val['type']}</td></tr>";
        }
        $mailcontent .= "</table>";
        //echo $mailcontent;
        apf_require_class('Tools_SendMail');
        Tools_SendMail::get_instance()->send('fionayu@anjukeinc.com',date('Y-m').'月份自动转为事假的数据！',$mailcontent);
    }

    /**
     * 获取没有结算日
     *
     * @access public
     * @return int
     */
    public function get_settlement_day() {
        $result = 28;
        $lastmonth = mktime(0,0,0,date('m') - 1,1,date('Y'));
        $lastmonth = date('Ym',$lastmonth);
        $sql = "SELECT settlement FROM month_special_setting WHERE month = $lastmonth";
        $b = $this->get_db_rows($sql,$this->readdb,array());
        if($b) {
            $result = substr($b[0]['settlement'],7,8);
        }
        return $result;
    }

    /**
     * 根据ID获取用户信息
     *
     * @param array|int $ids
     * @access public
     * @return array()
     */
    public function get_user_info_by_id($ids) {
        $result = array();
        if(empty($ids)) {
            return $result;
        }
        if(is_array($ids)) {
            $sql = "SELECT * FROM user_info WHERE user_id IN ($ids)";
        } else {
            $sql = "SELECT * FROM user_info WHERE user_id = $ids";
        }
        $result = $this->get_db_rows($sql, $this->readdb, array());
        return $result;
    }
    /**
     * 病假转事假
     * @param int $leave_id
     */
    private function update_day_record($leave_id){
        //update user_last_leave_record "上月未清数据记录"
        $this->report_bll->update_record_prev(array('leave_type '=>5),array('leave_id'=>$leave_id));
        //user_leave_daily "迟到公出出差早退表"
        $this->report_bll->update_record_curr(array('leave_type'=>5),array('leave_id'=>$leave_id));
        //user_leave_record_ext "用户请假记录每半天区分"
        $this->report_bll->update_record_next(array('am_type'=>5),array('am_leave_id'=>$leave_id));
        $this->report_bll->update_record_next(array('pm_type'=>5),array('pm_leave_id'=>$leave_id));
    }
}

